<template>
  <div class="task-dashboard">
    <header class="dashboard-header">
      <h2>任务 Dashboard</h2>
    </header>

    <!-- 筛选任务名称 -->
    <div class="task-filter">
      <label for="taskName">筛选任务名称：</label>
      <input
        id="taskName"
        v-model="filterName"
        @input="fetchTasks"
        placeholder="输入任务名称"
      />
    </div>

    <!-- 任务列表 -->
    <div class="task-list">
      <ul>
        <li v-for="task in filteredTasks" :key="task.id" class="task-item">
          <div class="card">
            <div class="card-content">
              <h4 class="task-title">{{ task.title }}</h4>
              <p class="task-desc">{{ task.description }}</p>
              <p class="task-deadline">截止日期：{{ task.deadline }}</p>
            </div>
            <div class="card-actions">
              <button class="btn btn-info" @click="viewTask(task)">查看详情</button>
              <button class="btn btn-primary" @click="joinTask(task.id)">加入任务</button>
            </div>
          </div>
        </li>
      </ul>
    </div>

    <!-- 任务详情弹窗 -->
    <div v-if="showTaskDetails" class="modal-overlay" @click.self="showTaskDetails = false">
      <div class="task-details-modal">
        <h3>{{ currentTask.title }}</h3>
        <p>{{ currentTask.description }}</p>
        <p>截止日期：{{ currentTask.deadline }}</p>
        <button class="btn btn-secondary" @click="showTaskDetails = false">关闭</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from '@/axiosInstance'; // 引入 Axios 实例

export default {
  name: "TaskDashboard",
  data() {
    return {
      tasks: [],         // 任务列表
      taskNames: {},     // 存储任务名称的对象
      filterName: "",    // 筛选条件
      currentTask: {},   // 当前选中的任务
      showTaskDetails: false, // 控制任务详情弹窗显示
    };
  },
  computed: {
    filteredTasks() {
      return this.tasks.filter(task => task.title.includes(this.filterName));
    }
  },
  methods: {
    async fetchTasks() {
      try {
        const user = this.$store.state.user || JSON.parse(localStorage.getItem("user"));
        if (!user || !user.user_id) {
          alert("用户未登录或用户信息缺失");
          this.$router.push("/login");
          return;
        }

        const response = await axios.get("http://39.105.217.183:8000/student/tasks/");
        console.log("返回数据：", response.data);
        if (response.data.status === "success") {
          this.tasks = response.data.data;
          // 存储任务名称
          this.tasks.forEach(task => {
            this.taskNames[task.id] = task.title;
          });
        } else {
          alert("任务获取失败：" + response.data.message);
        }
      } catch (error) {
        console.error("任务获取失败:", error.message || error);
        alert("任务获取失败，请稍后重试");
      }
    },
    viewTask(task) {
      this.currentTask = {...task};
      this.showTaskDetails = true;
    },
    async joinTask(taskId) {
      try {
        const user = this.$store.state.user || JSON.parse(localStorage.getItem("user"));
        if (!user || !user.username) {
          alert("用户未登录或用户信息缺失");
          this.$router.push("/login");
          return;
        }
        const studentUsername = user.username;
        const taskName = this.taskNames[taskId];
        console.log("学生用户名：", studentUsername);
        console.log("任务名称：", taskName);
        console.log("任务ID：", taskId);

        const response = await axios.post(`http://39.105.217.183:8000/tasks/${taskId}/join/`, {
          student_username: studentUsername,
        });
        if (response.data.status === "success") {
          alert("成功加入任务");
        } else if (response.data.status === "already_joined") {
          alert("您已加入该任务");
        } else {
          alert("加入任务失败：" + response.data.message);
        }
      } catch (error) {
        console.error("加入任务失败:", error.message || error);
        alert("加入任务失败，请稍后重试");
      }
    }
  },
  mounted() {
    this.fetchTasks();
  }
};
</script>

<style scoped>
/* 整体容器 */
.task-dashboard {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  font-family: 'Inter', sans-serif;
  color: #333;
  background: #f5f7fa;
}

/* 标题样式 */
.dashboard-header h2 {
  font-size: 2rem;
  color: #2563eb;
  margin-bottom: 20px;
  text-align: center;
}

/* 筛选区域 */
.task-filter {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 30px;
  background-color: #fff;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.task-filter label {
  margin-right: 10px;
  font-weight: 500;
}

.task-filter input {
  padding: 10px 15px;
  font-size: 1rem;
  border: 1px solid #ddd;
  border-radius: 5px;
  width: 300px;
  outline: none;
  transition: border-color 0.3s;
}

.task-filter input:focus {
  border-color: #2563eb;
}

/* 任务列表 */
.task-list ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.task-item {
  margin-bottom: 20px;
}

/* 卡片样式 */
.card {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s, box-shadow 0.3s;
}

.card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.card-content {
  padding: 20px;
}

.task-title {
  margin: 0 0 10px;
  font-size: 1.2rem;
  color: #2563eb;
}

.task-desc,
.task-deadline {
  margin: 5px 0;
  font-size: 0.95rem;
  color: #555;
}

/* 按钮样式 */
.card-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px 20px;
  background-color: #f1f5f9;
}

.btn {
  padding: 8px 15px;
  font-size: 0.9rem;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-info {
  background-color: #2563eb;
  color: #fff;
}

.btn-info:hover {
  background-color: #1e40af;
}

.btn-primary {
  background-color: #0d9488;
  color: #fff;
}

.btn-primary:hover {
  background-color: #0f766e;
}

.btn-secondary {
  background-color: #6b7280;
  color: #fff;
}

.btn-secondary:hover {
  background-color: #4b5563;
}

/* 任务详情弹窗及遮罩层 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.35);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.task-details-modal {
  background: #fff;
  padding: 30px 25px;
  border-radius: 10px;
  width: 90%;
  max-width: 600px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

.task-details-modal h3 {
  margin-top: 0;
  font-size: 1.5rem;
  color: #2563eb;
  margin-bottom: 15px;
}

.task-details-modal p {
  font-size: 1rem;
  margin-bottom: 10px;
  color: #555;
}

.task-details-modal button {
  margin-top: 20px;
}
</style>